package com.jluzh10.learning.web.controller;

import com.jluzh10.learning.domain.Reply;
import com.jluzh10.learning.domain.User;
import com.jluzh10.learning.service.ReplyService;
import com.jluzh10.learning.utils.ResponseData;
import com.jluzh10.learning.utils.qiniu.QiniuUtil;
import com.jluzh10.learning.web.converter.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author cj
 * @date 6/1/2019
 */
@Controller
@RequestMapping("reply")
@ResponseBody
public class ReplyController {

    private final ReplyService rs;

    @Autowired
    public ReplyController(ReplyService rs) {
        this.rs = rs;
    }

    /**
     * 查询一个回答下的所有回复
     * @param answerId
     * @return
     */
    @RequestMapping(value = "search",method = RequestMethod.GET)
    public ResponseData searchReplies(@RequestParam(name="answerId")Integer answerId){
        List<Reply> replies =  rs.searchReplies(answerId);
        if(replies!=null&&!replies.isEmpty()){
            return new ResponseData().success("查询评论成功").data(replies);
        } else {
            return new ResponseData().fail("评论为空");
        }

    }

    /**
     * 新增一个回复
     */
    @RequestMapping("add")
    public ResponseData addReplies(@LoginUser User user, Reply reply){

         if(user!=null){
             reply.setCreateTime(new Date());
             reply.setUserId(user.getId());

             int i = rs.addReply(reply);
             if(i >0){
                 return new ResponseData().success("更新一条回复成功");
             } else {
                 return new ResponseData().fail("更新回复失败");
             }
         } else {
             return new ResponseData().redirect("尚未登陆");
         }
    }

}
